//
// Created by 廖海龙 on 2025/4/8.
//

#include "HelloServerHelper.hpp"


int HelloServerHelper::getFreePort(int from, int to) {
    int sock_fd;
    struct sockaddr_in address{};

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_fd < 0) {
        return -1;
    }

    address.sin_family = AF_INET; // IPV4协议
    address.sin_addr.s_addr = htonl(INADDR_ANY); // 监听本地多有IP地址，INADDR_ANY表示所有网卡

    int port = from;
    int result;
    do {
        address.sin_port = htons(port++);
        result = bind(sock_fd, (const struct sockaddr *) &address, sizeof(address));
    } while (result < 0 && port <= to && errno == EADDRINUSE);

    if (result < 0) {
        close(sock_fd); // 关闭套接字，防止系统句柄不够用
        return -1;
    }

    close(sock_fd); // 关闭套接字，防止系统句柄不够用
    return port - 1;
}

bool HelloServerHelper::setNonBlock(int fd) {
    int nb = 1; // 0:清除 1:设置
    if (ioctl(fd, FIONBIO, &nb) == -1) {
        return false;
    }

    return true;
}

void HelloServerHelper::releaseThread(std::thread **thread) {
    std::thread *t = *thread;
    if (t) {
        if (t->joinable()) t->join();
    }
    delete t;
    *thread = nullptr;
}